package cn.iocoder.yudao.module.call.websocket;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import cn.iocoder.yudao.framework.common.enums.UserTypeEnum;
import cn.iocoder.yudao.framework.security.core.LoginUser;
import cn.iocoder.yudao.framework.websocket.core.listener.WebSocketMessageListener;
import cn.iocoder.yudao.framework.websocket.core.sender.WebSocketMessageSender;
import cn.iocoder.yudao.framework.websocket.core.util.WebSocketFrameworkUtils;
import cn.iocoder.yudao.module.call.enums.WebSocketConstants;
import cn.iocoder.yudao.module.call.websocket.message.CallModuleSendMessage;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.WebSocketSession;

import javax.annotation.Resource;

/**
 * 客服系统WebSocket消息监听器
 * 1. 监听客户上线 -> 查询或创建客户对象 -> 匹配客服 -> 获取欢迎语、场景配置 -> 自动执行消息发送
 * 2. 监听客户离线 -> 清除客服/客户缓存关系
 * 3. 监听客户消息 -> 创建对话记录
 * 4. 监听客户标签消息 -> 查询标签 -> 返回标签答复内容 -> 返回下一级标签列表
 * 5. 监听客户表单消息 -> 创建表单记录
 * -----
 *
 *
 * @author 芋道源码
 */
@Component
@Slf4j
public class CallModuleWebSocketMessageListener implements WebSocketMessageListener<CallModuleSendMessage> {

    @Resource
    private WebSocketMessageSender webSocketMessageSender;


    @Override
    public void onMessage(WebSocketSession session, CallModuleSendMessage message) {
        LoginUser loginUser = WebSocketFrameworkUtils.getLoginUser(session);
        log.info("onMsg ============ {}", message);
        String toUserId = StrUtil.concat(true, "97", StrUtil.fillBefore(String.valueOf(loginUser.getId()), '0', 10));
        webSocketMessageSender.send(UserTypeEnum.ADMIN.getValue(), Long.parseLong(toUserId), WebSocketConstants.MESSAGE_TYPE_RECEIVE, JSONUtil.toJsonStr(message));
    }


    @Override
    public String getType() {
        return WebSocketConstants.MESSAGE_TYPE_SEND;
    }
}
